import * as loginService from '@/api/login'

// 布局页面路由生成器
const generatorLayoutRouter = context => {
  const routerComponents = {}
  const replaceKeyRegex = /^.*\.{0,2}\/([^/]+)\.vue$/
  context.keys().forEach(item => {
    const key = item.replace(replaceKeyRegex, '$1')
    routerComponents[key] = context(item).default
  })
  return routerComponents
}

// 业务页面路由生成器
const generatorBusinessRouter = context => {
  const routerComponents = {}
  const replaceKeyRegex = /^.*\.{0,2}\/([^/]+)\.vue$/
  const replaceValueRegex = /^\.{0,2}\/(([^/]+\/?)+)\.vue$/
  context.keys().forEach(item => {
    const key = item.replace(replaceKeyRegex, '$1')
    const path = item.replace(replaceValueRegex, '$1')
    routerComponents[key] = () => import(`@/views/${path}`)
  })
  return routerComponents
}

// 前端路由汇总表
const constantRouterComponents = {
  // 布局基础页面
  ...generatorLayoutRouter(
    require.context('@/layouts', false, /^((\.{0,2}\/(?!_\w*\/?))[^/]+)+\.vue$/i)
  ),

  // 业务相关页面
  ...generatorBusinessRouter(
    require.context('@/views', true, /^((\.{0,2}\/(?!modules\/|_\w*\/?))[^/]+)+\.vue$/i)
  )
}

// 前端未找到页面路由
const notFoundRouter = {
  path: '*',
  redirect: '/404',
  hidden: true
}

// 根级菜单
const rootRouter = {
  key: '',
  name: 'index',
  path: '/',
  component: 'BasicLayout',
  redirect: '/',
  meta: {
    title: '首页'
  },
  children: []
}

/**
 * 转换树形结构
 * @param list 源数组
 * @param tree 树
 * @param parentId 父ID
 */
const listToTree = (list, tree, parentId) => {
  list.forEach(item => {
    // 判断是否为父级菜单
    if (item.parentId === parentId) {
      const child = {
        ...item,
        key: item.key || item.name,
        children: []
      }
      
      // 迭代 list，找到当前菜单相符合的所有子菜单
      listToTree(list, child.children, item.id)
      // 删掉不存在 children 属性
      if (child.children.length <= 0) {
        delete child.children
      }
      // push child
      tree.push(child)
    }
  })
}

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = token => {
  return new Promise((resolve, reject) => {
    loginService.getCurrentUserNav(token).then(res => {
      const { result } = res
      const menuNav = []
      const childrenNav = []
      // 后端数据, 根级树数组,根级 PID
      listToTree(result, childrenNav, '0')
      rootRouter.children = childrenNav
      menuNav.push(rootRouter)
      const routers = generator(menuNav)
      routers.push(notFoundRouter)
      resolve(routers)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * 动态加载路由对应页面的组件
 *
 * @param routerMap
 * @param component
 * @returns { 组件 }
 */
export const loadDynamicComponent = (component, key) => {
  return (
    (constantRouterComponents[component || key]) ||
    (() => import(`@/views/${component}`))
  )
}

/**
 * 格式化树形结构数据 生成 vue-router 层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap, parent) => {
  return routerMap.map(item => {
    const { title, show, hideChildren, hiddenHeaderContent, target, icon } = item.meta || {}
    const currentRouter = {
      // 路由path
      path: item.path || `${parent && parent.path || ''}/${item.key}`,
      // 路由名称
      name: item.name || item.key || '',
      // 路由组件
      component: loadDynamicComponent(item.component, item.key),
      // 路由meta
      meta: {
        icon: icon,
        title: title,
        target: target,
        hiddenHeaderContent: hiddenHeaderContent === undefined ? true : ((parent || {}).meta || {}).hiddenHeaderContent,
        permission: [item.name]
      }
    }
    // 是否设置了隐藏菜单
    if (show === false) {
      currentRouter.hidden = true
    }
    // 是否设置了隐藏子菜单
    if (hideChildren) {
      currentRouter.hideChildrenInMenu = true
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}
